/****************************************************************************
 * Copyright 2010 Huascar A. Sanchez                                        *
 *                                                                          *
 * Licensed under the Apache License, Version 2.0 (the "License");          *
 * you may not use this file except in compliance with the License.         *
 * You may obtain a copy of the License at                                  *
 *                                                                          *
 *     http://www.apache.org/licenses/LICENSE-2.0                           *
 *                                                                          *
 * Unless required by applicable law or agreed to in writing, software      *
 * distributed under the License is distributed on an "AS IS" BASIS,        *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
 * See the License for the specific language governing permissions and      *
 * limitations under the License.                                           *
 ****************************************************************************/
package com.gotobject.greatq;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static java.util.Arrays.asList;

/**
 * @author huascar.sanchez@gmail.com (Huascar A. Sanchez)
 */
class QuerySubmissionBuilderImpl implements QuerySubmissionBuilder {
    QuerySubmitterImpl querier;
    List<String>    sqls;
    String          key;

    QuerySubmissionBuilderImpl(QuerySubmitterImpl querier, String... sqls){
        this.sqls       = new ArrayList<String>(asList(sqls));
        this.querier    = querier;
    }

    String getKey(){
        return key;
    }

    String getSql(){
        ensureIsNotBatch();
        return sqls.get(ONLY_ELEMENT);
    }


    List<String> getBatchedSqls(){
        ensureIsBatch();
        return Collections.unmodifiableList(sqls);
    }

    private void ensureIsNotBatch() throws IllegalStateException {
        if(inBatchMode()) throw new IllegalStateException("error:in batch mode");
    }

    private void ensureIsBatch() throws IllegalStateException {
        if(!inBatchMode()) throw new IllegalStateException("error:not in batch mode");
    }

    boolean hasKey(){
        return key != null && !"".equalsIgnoreCase(key);
    }

    boolean inBatchMode(){
        return (sqls.size() > 1);
    }

    @Override
    public void as(String value) {
        addKey(value, inBatchMode() ? "error:batch key is null." : "error:key is null.");
    }

    private void addKey(String key, String value){
        if(key == null || "".equalsIgnoreCase(key)){
            querier.addError(value);
        }
        this.key = key;
    }

}
